package com.sprucetec.livechat.config;

import com.sprucetec.livechat.web.websocket.WebSocketChildChannelHandler;
import com.sprucetec.livechat.web.websocket.WebSocketServer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.nio.NioEventLoopGroup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

/**
 * @ClassName WebSocketConfig
 * @Description:
 * @Author Kenny
 * @Date 2020/4/2
 **/
@Configuration
public class WebSocketConfig {


    @Bean
    public CommonsMultipartResolver commonsMultipartResolver(){
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
        commonsMultipartResolver.setDefaultEncoding("UTF-8");
        commonsMultipartResolver.setMaxUploadSize(10485760);
        commonsMultipartResolver.setMaxInMemorySize(40960);
        return  commonsMultipartResolver;
    }


    @Value("${websocket.server.port}")
    private String nettyServerPort;

    @Autowired
    private WebSocketChildChannelHandler webSocketChildChannelHandler;

    /**
     * 用于处理客户端连接请求
     *
     * @return
     */
    @Bean("bossGroup")
    public NioEventLoopGroup bossGroup() {
        return new NioEventLoopGroup();
    }

    /**
     * 用于处理客户端I/O操作
     *
     * @return
     */
    @Bean("workerGroup")
    public NioEventLoopGroup workerGroup() {
        return new NioEventLoopGroup();
    }

    /**
     * 服务器启动引导类
     *
     * @return
     */
    @Bean("serverBootstrap")
    @Scope("prototype")
    public ServerBootstrap serverBootstrap() {
        return new ServerBootstrap();
    }

    /**
     * 自定义的Netty Websocket服务器
     *
     * @return
     */
    @Bean("webSocketServer")
    public WebSocketServer webSocketServer() {
        WebSocketServer webSocketServer = new WebSocketServer();
        webSocketServer.setPort(Integer.parseInt(nettyServerPort));
        webSocketServer.setChildChannelHandler(webSocketChildChannelHandler);
        return webSocketServer;
    }

}
